import Taro from "@tarojs/taro";
import { memo, useEffect, useState } from "react";
import { Picker, ScrollView, Text, View } from "@tarojs/components";
import { Popup, Button } from "@nutui/nutui-react-taro";
import { login, register } from "../../api/user";
import { setStore, getStore } from "../../utils/localStore";
import "./index.scss";
import AreaPicker from '../../components/address_picker'

export default function Login(props) {

  useEffect(() => {
    showPicker()
  })

  function showPicker() {

  }
  
  const [codeMobile, setCodeMobile] = useState("")
  const [areaIsVisible, setAreaIsVisible] = useState(false)
  const [region, setRegion] = useState(['云南省', '玉溪市', '红塔区'])
  function getUserInfo(e) {
    console.log(e);
  }

  function getPhoneNumber(e) {
    console.log(e);
    if(!e.detail.code){
      Taro.showModal({
        title:"您已经拒绝授权，请重新登录",
        showCancel:false
      })
      return false;
    }

    Taro.login({
      success: function (result) {
        login({ code: result.code }).then((res) => {
          if (res.code === 501) {
            setStore("token", res.msg);
            registerFn(e.detail.code)
          } else {
            loginSuccessCallback(res)
          }
        });
      }
    })

  }

  function registerFn(codeMobile) {
    Taro.getLocation({
      success(res) {
        getAddressInfo(res.longitude, res.latitude, codeMobile)
      },
      fail(err){
        setAreaIsVisible(!areaIsVisible)
        setCodeMobile(codeMobile)
      }
    })
  }

  async function getAddressInfo(longitude, latitude, codeMobile) {
    const { data } = await Taro.request({
      url: "https://restapi.amap.com/v3/geocode/regeo",
      method: 'get',
      data: {
        key: "677d1e9aa3b338a8b35c9498790f1bf8",
        location: longitude + "," + latitude,
      }
    })

    if (data.info === 'OK') {
      const { province, city, district } = data?.regeocode?.addressComponent
      register({ codeMobile, province, city, districts:district }).then(res => {
        loginSuccessCallback(res)
      })
    } else {
      // Taro.showToast({ title: '获取位置信息失败' })
    }
  }

  function loginSuccessCallback(res) {
    setStore("userInfo", res.data.userInfoDto);
    setStore("token", res.data.token);
    props?.close();
    Taro.showToast({ title: "登录成功", icon: "success" });
    setTimeout(() => {
      Taro.reLaunch({
        url: "/pages/home/index",
      });
    }, 800);
  }


  function onCancel() {
    console.log("cancel");
    setAreaIsVisible(true)
    // return;
    // if(!districts && areaIsVisible){
    //   Taro.showModal({
    //     title:'请选择常住地址'
    //   })
    //   return;
    // }
    // setAreaIsVisible(!areaIsVisible)
  }

  

  const [districts,setDistricts] = useState('')
  function getAddress(data){
    const province = data[0].text
    const city = data[1].text
    const districts = data[2].text
    setDistricts(districts)
    Taro.showLoading()
    register({ codeMobile, province, city, districts }).then(res => {
      loginSuccessCallback(res)
    }).finally(()=>{
      Taro.hideLoading()
    })
  }

  return (
    <>
      <Popup
        visible={props?.visible}
        style={{ height: "20%" }}
        position="bottom"
        onClose={() => {
          props?.close();
        }}
      >
        <View className="loginWrap">
          <Text className="title">消防安全学习平台</Text>
          <Button open-type="getPhoneNumber" onGetPhoneNumber={getPhoneNumber} type="info">
            手机号快捷登录
          </Button>

          {/* <Button open-type="chooseAvatar"  onGetUserInfoEventDetail={getUserInfo}  type="info">
          手机号快捷登录
        </Button> */}
        </View>
      </Popup>


      <AreaPicker 
      isVisible={areaIsVisible} 
      changeVisibel={() => setAreaIsVisible(!areaIsVisible)}
      // onCancel={onCancel}
      getAddress={getAddress}
       />
      {/* <View class="section__title">省市区选择器</View>
      <Picker mode="region" bindchange="bindRegionChange" value={region}>
        <View class="picker" onClick={showPicker}>
          当前选择：{region[0]}，{region[1]}，{region[2]}
        </View>
      </Picker> */}



    </>
  );
}
